package shuyu;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

//import com.mysql.jdbc.PreparedStatement;

import shuyu.Article;

public class ArticleDao {

	public static List<Article> QueryAllArticle(){
		Connection conn = DB.getConnection();
		List<Article> articles = new ArrayList<Article>();
		try {
			String sql = "SELECT ID, TITLE, CONTEXT FROM ARTICLE";
			Statement stat = conn.createStatement();
			ResultSet rs = stat.executeQuery(sql);
			System.out.println(rs);
			while (rs.next()) {
				Article article = new Article();
				article.setId(rs.getInt("ID"));
				article.setTitle(rs.getString("TITLE"));
				article.setContext(rs.getString("CONTEXT"));
				articles.add(article);
			}
			rs.close();
			stat.close();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			try {
				if (conn != null) {
					conn.close();
					conn = null;
				}
			} catch (Exception ex) {
			}
		}
		return articles;
	}
	public void addArticle(String title, String context) {
		Connection conn = DB.getConnection();
		String sql = "insert into article(title, context) values (?, ?)";
		try {
			PreparedStatement smt = conn.prepareStatement(sql);
			smt.setString(1, title);
			smt.setString(2, context);
			smt.executeUpdate();
			
			smt.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}
	// 修改
	public void  editArticle(String title, String context, int id) {
		Connection conn = DB.getConnection();
		String sql = "update article set title = ?, context = ? where id = ?";
		try {
			PreparedStatement smt = conn.prepareStatement(sql);
			smt.setString(1, title);
			smt.setString(2, context);
			smt.setInt(3, id);
			smt.executeUpdate();
			
			smt.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}	
		 
	}
	//删除
	public void delArticle(int id) {
		Connection conn = DB.getConnection();
		try {
			PreparedStatement smtPreparedStatement = conn.prepareStatement("delete from article where id = ?");
			smtPreparedStatement.setInt(1, id);
			smtPreparedStatement.executeUpdate();
			smtPreparedStatement.close();
			conn.close();
			
		} catch (SQLException e) {
			e.printStackTrace();
		}		
		
	}
}
